# -*- coding: utf-8 -*-
# File : windows_ansible.py
# Author: taoyahui
# Date : 2021/8/11
import sys
sys.path.append('..')
import ansible.constants as C
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.module_utils.common.collections import ImmutableDict
from ansible.inventory.manager import InventoryManager
from ansible.parsing.dataloader import DataLoader
from ansible.playbook.play import Play
from ansible.plugins.callback import CallbackBase
from ansible.vars.manager import VariableManager
from ansible import context
from ansible.inventory.host import Host
from os import path
from utils.path_util import get_root_dir
from utils import mysql_util
from application_factory.models import InventoryCls

def dynamic_exec(play_source, inventory_list):
    """
    动态执行windows主机的操作()
    :param inventory_list:
    :param play_source:
    :param hosts: e.g ['192.168.50.199', '192.168.50.219']
    :return:
    """
    loader = DataLoader()
    inventory = InventoryManager(loader=loader, sources=(path.join(get_root_dir(), 'playbook', 'hosts'),))

    variable_manager = VariableManager(loader=loader, inventory=inventory)

    for m_inventory in inventory_list:
        my_host = m_inventory.ip
        variable_manager.set_host_variable(host=my_host, varname="ansible_ssh_host", value=my_host)
        variable_manager.set_host_variable(host=my_host, varname="ansible_ssh_port", value=m_inventory.port)
        variable_manager.set_host_variable(host=my_host, varname="ansible_ssh_user", value=m_inventory.username)
        variable_manager.set_host_variable(host=my_host, varname="ansible_ssh_pass", value=m_inventory.password)
        variable_manager.set_host_variable(host=my_host, varname="ansible_connection", value='winrm')
        variable_manager.set_host_variable(host=my_host, varname="ansible_winrm_server_cert_validation",
                                           value='ignore')

        inventory.add_host(host=my_host, group='windows', port=m_inventory.port)



    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
    passwords = {}  # dict(vault_pass='123456')
    # results_callback = ResultsCollectorJSONCallback()
    tqm = TaskQueueManager(
        inventory=inventory,
        variable_manager=variable_manager,
        loader=loader,
        passwords=passwords,
        # stdout_callback=results_callback,  # Use our custom callback instead of the ``default`` callback plugin, which prints to stdout
    )
    try:
        result = tqm.run(play)  # most interesting data for a play is actually sent to the callback's methods
    finally:
        # we always need to cleanup child procs and the structures we use to communicate with them
        tqm.cleanup()
        if loader:
            loader.cleanup_all_tmp_files()

    return result
